package edu.biwu.cookie05;

import edu.biwu.utils.CookieUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 记录上次访问时间案例
 */
@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        //1.查找一个名称为lastVisited的cookie
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtils.getCookie(cookies, "lastVisited");

        if (cookie == null) {
            //向浏览器响应 "欢迎第一次访问"
            response.getWriter().write("欢迎第一次访问");
        } else {
            //说明首次访问,创建一个lastVisitedCookie记录当前访问时间
            //取出cookie中记录的时间,响应给浏览器
            String dateStr = cookie.getValue();

            //对dateStr进行解码,编码出原始值
            String decodeDate = URLDecoder.decode(dateStr, "UTF-8");
            response.getWriter().write("您上次访问时间:" + decodeDate);
        }
        //无论是第一次,第二次,第三次,....第n次访问,都需要将当前系统时间设置到cookie,响应给浏览器
        String formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

        //再将日期放入cookie前,先进行编码,防止cookie不支持某些字符
        String encodeDate = URLEncoder.encode(formatDate, "UTF-8");

        Cookie lastVisitedCookie = new Cookie("lastVisited", encodeDate);
        lastVisitedCookie.setMaxAge(7 * 24 * 60 * 60); //设置最大存活时间为7天
        lastVisitedCookie.setPath(request.getContextPath());
        response.addCookie(lastVisitedCookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
